﻿using Abp.Application.Services.Dto;
using shenghua.Basics.MemberLevels;
using shenghua.Basics.MemberLevelSetting.Dto;
using shenghua.Common.CustomValueType;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace shenghua.Basics.MemberLevelSetting
{
    public class MemberLevelSettingAppService: shenghuaAppServiceBase, IMemberLevelSettingAppService
    {
        private readonly MemberLevels.MemberLevelManager _memberLevelManager;

        public MemberLevelSettingAppService(
            MemberLevels.MemberLevelManager memberLevelManager)
        {
            _memberLevelManager = memberLevelManager;
        }

        public async Task<MemberLevelDto> Create(CreateMemberLevelDto input)
        {
            MemberLevel memberLevel = new MemberLevel
            {
                Name = input.Name,
                DisplayName = input.DisplayName,
                NeededXPValue = input.NeededXPValue,
                Discount = input.Discount,
                Roles = new ValueArray<string>(input.Roles)
            };
            await _memberLevelManager.Add(memberLevel);
            return GetMemeberLevelDto(memberLevel);
        }

        public async Task<MemberLevelDto> Update(UpdateMemberLevelDto input)
        {
            MemberLevel memberLevel = await _memberLevelManager.Get(input.Id);
            memberLevel.Name = input.Name;
            memberLevel.DisplayName = input.DisplayName;
            memberLevel.NeededXPValue = input.NeededXPValue;
            memberLevel.Discount = input.Discount;
            memberLevel.Roles = new ValueArray<string>(input.Roles);
            await _memberLevelManager.Update(memberLevel);
            return GetMemeberLevelDto(memberLevel);
        }

        public async Task DeleteLast()
        {
            await _memberLevelManager.DeleteLast();
        }

        public async Task<List<MemberLevelDto>> GetAll()
        {
            List<MemberLevel> memberLevels = await _memberLevelManager.GetAll();
            return memberLevels.Select(r => GetMemeberLevelDto(r)).ToList();
        }

        private MemberLevelDto GetMemeberLevelDto(MemberLevel memberLevel)
        {
            return new MemberLevelDto
            {
                Id = memberLevel.Id,
                Name = memberLevel.Name,
                Discount = memberLevel.Discount,
                DisplayName = memberLevel.DisplayName,
                Level = memberLevel.Level,
                NeededXPValue = memberLevel.NeededXPValue,
                Roles = memberLevel.Roles.Items
            };
        }
    }
}
